package com.cicadamob.contact.api.service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.map.MappingIterator;
import org.codehaus.jackson.map.ObjectMapper;

import android.content.ContentValues;
import android.content.Context;
import android.os.Handler;
import android.util.Log;

import com.cicadamob.contact.api.Utils.ContactConfig;
import com.cicadamob.contact.api.Utils.StringUtil;
import com.cicadamob.contact.api.Utils.Endecryption.EndecryptionUtil;


/**
 * 增量更新
 * @author Administrator
 *
 */
public class UpdateCompanyRunnable implements Runnable {
	private final String ioMessage = "通信异常";
	private final String nullSyncinfo = "获取本地客户经理助手同步信息失败";
	private UpdateState updateState = new UpdateState();
	private ObjectMapper mapper = new ObjectMapper();
	private int pagesize=1000;
	private String strCount;
	private int count = 0;
	private int page = 1;
	private Context mContext;
	private Handler mHandler;
	private int what;
	public UpdateCompanyRunnable(Context mContext,Handler mHandler,int what){
		this.mContext=mContext;
		this.mHandler=mHandler;
		this.what=what;
	}
		
	@Override
	public void run() {
		// TODO Auto-generated method stub
		String[] sync_info=ContactDbHelper.getInstance().getAysnInfo();
		_opertorUpdate(sync_info,page, mContext);
		if(count > 0) {
			for(int i = 1;i<count;i++) {
				page+=1;
				_opertorUpdate(sync_info,page, mContext);
			}
			
		}
		mHandler.obtainMessage(what).sendToTarget();
	}
	
	/**
	 * 执行同步企业通讯录操作
	 * @param page
	 */
	private void _opertorUpdate(String[] sync_info,int pageIndex,Context context) {
		//获取服务端同步信息
		if(StringUtil.isEmpty(sync_info[0]) || StringUtil.isEmpty(sync_info[1]) || StringUtil.isEmpty(sync_info[2])) {
			updateState.setExceptionMessage(nullSyncinfo);
			context.deleteFile(ContactDbHelper.DBFILE);
			ContactDbHelper.getInstance().setDataBaseIsNull();
			return;
			
		}
		Log.v("my", "数据版本信息"+sync_info[0]+"-"+sync_info[1]+"-"+sync_info[2]);
//		String client_company=ContactDbHelper.getInstance().findClintCompanyCodes();
		String url = StringUtil.getBuffer().append(ServerUrl.COMPANY_SYNC_DB3_URL).append("?id=" + sync_info[0])
		  																  .append("&pageIndex=" + pageIndex)
		  																  .append("&pageSize=" + pagesize)
		  																  .append("&seq=" + sync_info[1])
		  																  .append("&timestamp=" + sync_info[2])
		  																  .append("&kehu_id=" + sync_info[3])
		  																  .append("&kehu_timestamp=" + sync_info[4])
//		  																  .append("&orgId=" + AppConfig.get)
		  																  .append("&mobile=" + ContactConfig.getCompanyValidMobile(context))
		  																  .append("&imsi=" + ContactConfig.getIMSI(context))
		  																  .append("&imei=" + ContactConfig.getIMEI(context))
		  																  .append("&str_1=null")
		  																  .append("&str_2=null")
		  																  .append("&str_3=null")
		  																  .append("&companyId=").append(ContactConfig.getCompanyValidCompanyId(context))
		  																  .append("&fromid=").append(ContactConfig.getMobile(context))
		  																  /*.append("&client_company=" + client_company)*/.toString();
		
		Log.v("url", "===url="+url);
		String fileName = ContactConfig.getCompanyValidMobile(context) + "_" + pageIndex + ".txt";
		//下载需要更新文件
//		long start=System.currentTimeMillis();
	 
		String encdata =ContactConfig.getCompanyValidMobile(context) + ";" + ContactConfig.getIMSI(context) + ";"
				+ ContactConfig.getIMEI(context) + ";" + StringUtil.getRandomStr(7) + ";"
				+ StringUtil.getStrDate(new Date(), "yyyy-MM-dd hh:mm:ss");
		String des = EndecryptionUtil.encode3DesAndBase64(encdata,
				ContactHttpClient.KEY);
		
		Map<String,String> params=new HashMap<String, String>();
		params.put("mobile", ContactConfig.getCompanyValidMobile(context));
		params.put("imsi", ContactConfig.getIMSI(context));
		params.put("imei", ContactConfig.getIMEI(context));
		
		params.put("authentication", StringUtil.encode(des));
		params.put("Connection", "close");
		
		int status = ContactHttpClient.downloadFile(url,params,FilePath.DOWNLOAD_PATH,fileName);
		MappingIterator<SyncCompanyJSON> iterator = null;
		long end=System.currentTimeMillis();
//		Log.v("time", "status="+status+"=======_opertorUpdate+pageIndex="+pageIndex+"+网络用时="+(end-start)/1000+"s");
		if(status == 200) {
			try {
				//解析下载下来的的json文件
				iterator = parseJsonFile(fileName);
				//将解析后的文件进行数据库同步操作
				opertorUpdate(iterator,context,FilePath.DOWNLOAD_PATH+fileName);
				long end1=System.currentTimeMillis();
				Log.v("time", "_opertorUpdate+pageIndex="+pageIndex+"+解析插入数据库="+(end1-end)/1000+"s");
			} catch (ServerException e) {
				updateState.setExceptionMessage(e.getMessage());
			}
		} else if(status == 806){
//			updateState.setExceptionMessage(String.valueOf(HttpUtils.CHANGEDEPARTMENTCODE));
			ContactConfig.getContext().deleteFile(ContactDbHelper.DBFILE);
			ContactDbHelper.reloadDataBase();
			ContactDbHelper.getInstance().reloadDB();
		} else {
//			updateState.setExceptionMessage(ActivationCode.EXCEPTIONMESSAGE.showMsg(String.valueOf(status)));
		}
	}
	
	/**
	 * 解析下载下来的需要更新的json文件
	 * @param filename
	 * @return
	 * @throws ServerException
	 */
	private MappingIterator<SyncCompanyJSON> parseJsonFile(String filename)throws ServerException {
		JsonFactory factory = new JsonFactory();
		MappingIterator<SyncCompanyJSON> iterator = null;
		org.codehaus.jackson.JsonParser jp = null;
		File file = null;
		try {
			file = new File(FilePath.DOWNLOAD_PATH + filename);
			jp = factory.createJsonParser(file);
			iterator = mapper.readValues(jp, SyncCompanyJSON.class);
			
		} 
		catch (IOException e) {
			
			throw new ServerException(ioMessage);
		} catch(Exception e){
			e.printStackTrace();
		}finally {
			if(null != jp) {
				if(jp.isClosed()) {
					try {
						jp.close();
					
					} catch (IOException e) {
					
						throw new ServerException(ioMessage);
						
					}
				}
			}
			/*if(file.exists()) {
				file.delete();//miaozz delete
			}*/
		}
		return iterator;
	}
	
	/**
	 * 执行更新数据库操作
	 * @param iterator
	 * @return
	 * @throws ServerException
	 */
	private void opertorUpdate(MappingIterator<SyncCompanyJSON> iterator,Context context,String filePath)throws ServerException {
		ContentValues values = new ContentValues();
		SyncCompanyJSON json_value = null;
		  int i=0;

		   long start1=System.currentTimeMillis();
		   List<String> sqlList=new ArrayList<String>();
		if(null != iterator) {
			 boolean hasChangeCompanyTree=false;
			 boolean hasChangeClient=false;
			 SyncCompanyJSON tongshijson=null;//同事的
			 SyncCompanyJSON kehujson=null;//客户的
			try{
			   
				while(iterator.hasNext()) {
					
					json_value = iterator.next();
					if(StringUtil.isEmpty(strCount)) {
						strCount = json_value.getPageCount();
						count = Integer.parseInt(strCount);
					}
					//long start=System.currentTimeMillis();
					sqlList.add(json_value.getStrSql());
					if(ContactDbHelper.getInstance().hasChangeCompanyTree(json_value.getStrSql())){
						hasChangeCompanyTree=true;
						tongshijson=json_value;
					}
//					if(ContactDbHelper.getInstance().hasChangeClientTree(json_value.getStrSql())){
//						hasChangeClient=true;
//						kehujson=json_value;
//					}
					//ContactDbHelper.getInstance().executeSQL(json_value.getStrSql());
				/*	long end=System.currentTimeMillis();
					Log.e("my", "插入一条数据用时"+(end-start));
					i++;
					Log.v("my", "插入数据库   "+ i + json_value.getStrSql());*/
				}
			
			}catch (Exception e) {
				e.printStackTrace();
				Log.v("my", "插入数据库异常  ");
				//throw new ServerException(dbMessage);
			}finally {
				ContactDbHelper.getInstance().executesql(sqlList);
				//生成同事组织路径
				if(hasChangeCompanyTree){
					ContactDbHelper.getInstance().createComPanyTreePath();
				}
				//生成客户组织路径
				if(hasChangeClient){
					ContactDbHelper.getInstance().createClientTreePath();;
				}
				
				
				if(tongshijson != null) {
					//执行完操作后.更新同步信息表
					Log.v("my", "插入数据库结束   ");
					values.clear();
					values.put("id", tongshijson.getId());
					values.put("seq", tongshijson.getSeq());
					values.put("type", 0);
					values.put("timestamp", tongshijson.getTimestamp());
					Log.e("my", "插入数据库结束  插入后的版本信息"+tongshijson.getId()+"---"+tongshijson.getSeq()+"---"+tongshijson.getTimestamp());
					ContactDbHelper.getInstance().update(values);
					long end2=System.currentTimeMillis();
					Log.e("my", "插入"+i+"条数据用时"+(end2-start1));
					 
				}
				
				if(kehujson != null) {
					//执行完操作后.更新同步信息表
					Log.v("my", "插入数据库结束   ");
					values.clear();
					values.put("id", kehujson.getId());
					values.put("seq", kehujson.getSeq());
					values.put("type", 1);
					values.put("timestamp", kehujson.getTimestamp());
					Log.e("my", "插入数据库结束  插入后的版本信息"+kehujson.getId()+"---"+kehujson.getSeq()+"---"+kehujson.getTimestamp());
					ContactDbHelper.getInstance().update(values);
					long end2=System.currentTimeMillis();
					Log.e("my", "插入"+i+"条数据用时"+(end2-start1));
					 
				}
				File file = new File(filePath);
				if (file.exists()) {
					file.delete();
				}
			}
		}
	}
	
	
	
	
}
